- pointers contain memory address of variable. Note that we can not use simply int, float, double data types to store the address, as address require different kind of data to store.
Note:
General rule is "use reference in c++ over pointers, use pointers only if you have to". Pointers are avoided unless they are necessary.
Recap:
- variables are declared with : int x=5; float y=5.0;
Have a look at Data modifiers to know more.
- Declaration of pointer: int * p = &x; here p is pointer variable which will store the address of variable 'x' where as the '* p' contains the value stored in varialbe 'x'(this is called as dereferencing)
- So 'p' is integer pointer, '* p' is integer.
- We define the pointer using '* ' and dereference using the same '* ' but these don't have same meaning.
-
The reason we want to use pionters:
- If we need multiple varialbes (x and * p) to talk about same area of memory, this is commonly used for functions for passing data.
-
In this way we can allow change of value a variable holds by using pointers in functions and changing value of the * p , which will reflect outside the function as well.
#include<iostream> void fun(int *p) { *p=20; } void main() { int x=30; int *y=&x; //here y is pointer variable which will store address of variable 'x' fun(y); std::cout<<x; //it will print 20 , since the value at address is changed in function, it can be useful. }